package frame.system.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import frame.base.BaseConstant;
import frame.base.BaseService;
import frame.base.BootstrapTable;
import frame.system.mapper.DeptMapper;
import frame.system.mapper.UserMapper;
import frame.system.qo.AuthQo;
import frame.system.to.Dept;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.common.Mapper;

import java.util.List;


/**
 * Dept 模块服务类
 * <br>
 * @author PeiWentao
 * @since 2020-06-03 16:42
 */
@Service
public class DeptService extends BaseService<Integer, Dept, AuthQo> {

	@Autowired
    private DeptMapper deptMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    protected Mapper<Dept> mainMapper() {
        return deptMapper;
    }

    @Override
	public BootstrapTable<Dept> pageList(final AuthQo qo) {
        //分页查询
        Page<Dept> page = PageHelper.startPage(qo.page(), qo.size()).doSelectPage(() -> {
            deptMapper.pageList(qo);
        });
        return new BootstrapTable<Dept>(page.getTotal(),page.getResult());
	}

    public List<Dept> allList() {
        final AuthQo qo = new AuthQo();
        qo.setValid(BaseConstant.TO_VALID);
        qo.setOrderStr("id asc");
        return deptMapper.pageList(qo);
    }

    @Transactional
    @Override
    public int remove(Integer id) {
        // 将改部门下的员工转移到临时部门
        userMapper.updateDeptToDefault(id);
        return super.remove(id);
    }

    @Override
    protected void preAdd(Dept dept) {
        this.perDept(dept);
        super.preAdd(dept);
        dept.setId(null);
    }

    @Override
    protected void preUpdate(Dept dept) {
        this.perDept(dept);
        super.preUpdate(dept);
    }

    @Override
    protected Dept newInstanceT(Integer id) {
        return new Dept(id);
    }

    // managerPhone : "" -> null
    private void perDept(Dept dept) {
        if (StringUtils.isEmpty(dept.getManagerPhone())) dept.setManagerPhone(null);
    }
}
